package com.iguo.tube;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@SpringBootTest
public class FileDeletionScheduler {


  @Value("${upload.cache}")
  String directoryPath;
  @Test
  public void fileDeletionScheduler() {
    String directoryPath = "E:\\Desktop\\tubeRecord";
    List<String> fileNames = new ArrayList<>();
    // 要删除的文件路径
    File directory = new File(directoryPath);
    if (directory.isDirectory()) {
      // 列出目录中的文件
      File[] files = directory.listFiles();
      if (files != null) {
        System.out.println("目录中的文件:");
        for (File file : files) {
          // 只打印文件名
          if (file.isFile()) {
            String dateString = file.getName();
            String datePart = dateString.split(" ")[0].replace("_", " ");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
            LocalDateTime parsedDate = LocalDateTime.parse(datePart, formatter);
            LocalDateTime currentDateTime = LocalDateTime.now();
            LocalDateTime fiveMinutesBeforeNow = currentDateTime.minusMinutes(3);
            if (parsedDate.isBefore(fiveMinutesBeforeNow)) {
              System.out.println("文件" + dateString + "存储时间超时，已删除");
              fileNames.add(file.getName());
            }
          }
        }
      } else {
        System.out.println("目录为空或无法访问。");
      }
    } else {
      System.out.println(directoryPath + " 不是一个有效的目录路径。");
    }
    for (String fileName : fileNames) {
      File fileToDelete = new File(directoryPath + "\\" + fileName);
      if (fileToDelete.exists()) {
        fileToDelete.delete();
      } else {
        System.out.println("文件不存在: " + fileToDelete);
      }

    }
  }

  @Test
  public void delete(){
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    // 定义定时任务
    Runnable deleteTask = this::fileDeletionScheduler;
    // 每隔 10 秒执行一次删除任务
    scheduler.scheduleAtFixedRate(deleteTask, 0, 10, TimeUnit.SECONDS);
    try {
      // 运行 30 秒后关闭调度器
      TimeUnit.SECONDS.sleep(30);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      scheduler.shutdown();
    }
  }
}
